package com.nwpu.am.controller.admin;

import com.nwpu.am.constant.ErrorConstant;
import com.nwpu.am.pojo.dto.KnowledgeDTO;
import com.nwpu.am.pojo.dto.page.KnowledgePageDTO;
import com.nwpu.am.pojo.entity.Knowledge;
import com.nwpu.am.pojo.entity.Rule;
import com.nwpu.am.result.PageResult;
import com.nwpu.am.result.Result;
import com.nwpu.am.service.KnowledgeService;
import com.nwpu.am.service.RuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Objects;

/**
 * KnowledgeController
 *
 * @author Fbf
 * @version 1.0
 * {@code @date} 2024/6/5
 */

@RestController
@RequestMapping("/knowledge")
@Slf4j
@Api(tags = "知识库接口")
public class KnowledgeController {

    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private RuleService ruleService;

    @GetMapping("/selectPage")
    @ApiOperation("展示知识库")
    public Result<PageResult<Knowledge>> page(KnowledgePageDTO knowledgePageDTO) {
        log.info("知识分页查询，参数为：{}", knowledgePageDTO);
        PageResult<Knowledge> pageResult = knowledgeService.pageQuery(knowledgePageDTO);
        return Result.success(pageResult);
    }

    @PostMapping("/add")
    @ApiOperation("添加知识")
    public Result<String> add(@RequestBody @Validated KnowledgeDTO knowledgeDTO) {
        return knowledgeService.addKnowledge(knowledgeDTO) == 1 ?
                Result.success() :
                Result.error(ErrorConstant.ADD_WRONG);
    }

    @DeleteMapping("/delete/{knowledgeId}")
    @ApiOperation("删除知识")
    public Result<String> deleteById(@PathVariable("knowledgeId") Long knowledgeId) {
        int ret = knowledgeService.deleteKnowledge(knowledgeId);
        ArrayList<Rule> rules = ruleService.getAllRule();
        for (Rule r : rules) {
            if (Objects.equals(r.getPremiseKnowledgeId(), knowledgeId) || Objects.equals(r.getConclusionKnowledgeId(), knowledgeId)) {
                ruleService.deleteRule(r.getRuleId());
            }
        }
        return ret == 1 ?
                Result.success() :
                Result.error(ErrorConstant.DELETE_WRONG);
    }

    @PostMapping("/select/{knowledgeId}")
    @ApiOperation("查找知识")
    public Result<Knowledge> selectById(@PathVariable("knowledgeId") Long knowledgeId) {
        return Result.success(knowledgeService.selectById(knowledgeId));
    }

    @PutMapping("/update")
    @ApiOperation("更新知识")
    public Result<String> update(@RequestBody @Validated Knowledge knowledge) {
        return knowledgeService.update(knowledge) == 1 ?
                Result.success() :
                Result.error(ErrorConstant.UPDATE_WRONG);
    }
}
